<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>当日商品出入库统计</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="/css/index.css">
    <!-- 引入组件库 -->
    <script src="/js/vue.js"></script>
    <script src="/js/echarts.js"></script>
    <script src="/js/index.js"></script>
    <script src="/js/axios.min.js"></script>
    <style>
        /* 保持原有样式不变 */
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
        }
        .page-title {
            font-size: 20px;
            font-weight: 600;
            color: #1f2d3d;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e9e9e9;
        }
        .stat-container {
            padding: 0;
        }
        .stat-cards {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .stat-card {
            flex: 1;
            background: #fff;
            border-radius: 6px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
            min-width: 250px;
            transition: transform 0.3s ease;
        }
        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
        }
        .card-title {
            color: #666;
            font-size: 14px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
        }
        .card-title i {
            margin-right: 6px;
            font-size: 16px;
        }
        .card-value {
            font-size: 28px;
            font-weight: 600;
            margin: 8px 0;
            transition: color 0.3s ease;
        }
        .card-desc {
            color: #8c8c8c;
            font-size: 13px;
            display: flex;
            justify-content: space-between;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px dashed #f0f0f0;
        }
        .charts-container {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
            height: 400px;
        }
        .chart-wrapper {
            flex: 1;
            background: #fff;
            border-radius: 6px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        .chart-title {
            text-align: center;
            margin-bottom: 15px;
            color: #333;
            font-size: 16px;
            font-weight: 500;
            padding-bottom: 10px;
            border-bottom: 1px solid #f0f0f0;
        }
        .chart-content {
            width: 100%;
            height: calc(100% - 40px);
        }
        .el-table {
            margin-top: 0;
            border-radius: 6px;
            overflow: hidden;
        }
        .el-table th {
            background-color: #f7f8fa;
            font-weight: 500;
        }
        .header {
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 15px;
            border-bottom: 1px solid #e9e9e9;
        }
        .tab-container {
            background: #fff;
            border-radius: 6px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }
        .el-tabs__header {
            background-color: #f7f8fa;
            padding-left: 20px;
        }
        .el-tabs__content {
            padding: 15px 20px;
        }
        .el-date-editor {
            width: 200px;
        }
        .loading-mask {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            opacity: 0;
            transition: opacity 0.3s ease;
            pointer-events: none;
        }
        .loading-mask.active {
            opacity: 1;
            pointer-events: auto;
        }
        .loading-content {
            text-align: center;
        }
        .loading-icon {
            font-size: 36px;
            color: #1890ff;
            margin-bottom: 10px;
            animation: spin 1.5s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 加载遮罩 -->
    <div class="loading-mask" :class="{active: loading}">
        <div class="loading-content">
            <i class="el-icon-loading loading-icon"></i>
            <div>正在加载统计数据...</div>
        </div>
    </div>

    <div class="stat-container">
        <div class="header">
            <h2 class="page-title">当日商品出入库统计</h2>
            <el-date-picker
                    v-model="statDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                    @change="loadStatData"
                    style="margin-right: 10px"
            ></el-date-picker>
            <el-button type="primary" @click="loadStatData" icon="el-icon-refresh">
                刷新数据
            </el-button>
        </div>

        <!-- 统计卡片 -->
        <div class="stat-cards">
            <div class="stat-card">
                <div class="card-title">
                    <i class="el-icon-download"></i>当日入库总数
                </div>
                <div class="card-value" style="color: #00b42a">{{ inTotalCount }}</div>
                <div class="card-desc">
                    <span>总金额：¥{{ inTotalAmount }}</span>
                    <span>件数统计</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="card-title">
                    <i class="el-icon-upload"></i>当日出库总数
                </div>
                <div class="card-value" style="color: #ff4d4f">{{ outTotalCount }}</div>
                <div class="card-desc">
                    <span>总金额：¥{{ outTotalAmount }}</span>
                    <span>件数统计</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="card-title">
                    <i class="el-icon-refresh"></i>当日库存变动
                </div>
                <div class="card-value" :style="changeCount >= 0 ? 'color: #00b42a' : 'color: #ff4d4f'">
                    {{ changeCount >= 0 ? '+' + changeCount : changeCount }}
                </div>
                <div class="card-desc">
                    <span>净变动：{{ changeCount }} 件</span>
                    <span>更新：{{ updateTime }}</span>
                </div>
            </div>
        </div>

        <!-- 图表展示 -->
        <div class="charts-container">
            <!-- 入库扇形图 -->
            <div class="chart-wrapper">
                <div class="chart-title">{{ formatDate(statDate) }} 入库商品分布</div>
                <div id="inPieChart" class="chart-content"></div>
            </div>

            <!-- 出库扇形图 -->
            <div class="chart-wrapper">
                <div class="chart-title">{{ formatDate(statDate) }} 出库商品分布</div>
                <div id="outPieChart" class="chart-content"></div>
            </div>
        </div>

        <!-- 明细数据 -->
        <div class="tab-container">
            <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane label="入库明细" name="in">
                    <el-table
                            :data="inDetailList"
                            border
                            v-loading="tableLoading.in"
                            element-loading-text="加载入库明细中..."
                            empty-text="暂无入库记录">
                        <el-table-column prop="productName" label="商品名称" width="180"></el-table-column>
                        <el-table-column prop="quantity" label="入库数量" width="120"></el-table-column>
                        <el-table-column prop="price" label="单价(元)" width="120" :formatter="formatPrice"></el-table-column>
                        <el-table-column prop="amount" label="总金额(元)" width="140" :formatter="formatPrice"></el-table-column>
                        <el-table-column prop="completeTime" label="入库时间"></el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="出库明细" name="out">
                    <el-table
                            :data="outDetailList"
                            border
                            v-loading="tableLoading.out"
                            element-loading-text="加载出库明细中..."
                            empty-text="暂无出库记录">
                        <el-table-column prop="productName" label="商品名称" width="180"></el-table-column>
                        <el-table-column prop="quantity" label="出库数量" width="120"></el-table-column>
                        <el-table-column prop="price" label="单价(元)" width="120" :formatter="formatPrice"></el-table-column>
                        <el-table-column prop="amount" label="总金额(元)" width="140" :formatter="formatPrice"></el-table-column>
                        <el-table-column prop="completeTime" label="出库时间"></el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            // 统计日期（默认当天）
            statDate: new Date().toISOString().split('T')[0],
            // 入库统计
            inTotalCount: 0,
            inTotalAmount: '0.00',
            // 出库统计
            outTotalCount: 0,
            outTotalAmount: '0.00',
            // 变动统计
            changeCount: 0,
            updateTime: '',
            // 明细数据
            inDetailList: [],
            outDetailList: [],
            // ECharts实例
            inPieChart: null,
            outPieChart: null,
            // 当前激活的标签页
            activeTab: 'in',
            // 加载状态
            loading: false,
            tableLoading: {
                in: false,
                out: false
            }
        },
        created() {
            // 初始化时加载当天数据
            this.loadStatData();
        },
        methods: {
            // 格式化日期显示
            formatDate(dateStr) {
                if (!dateStr) return '';
                const date = new Date(dateStr);
                return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
            },

            // 格式化价格
            formatPrice(row, column, value) {
                return value ? '¥' + parseFloat(value).toFixed(2) : '¥0.00';
            },

            // 处理标签页切换
            handleTabClick(tab) {
                this.activeTab = tab.name;
            },

            // 加载统计数据
            loadStatData() {
                // 显示加载中
                this.loading = true;
                this.tableLoading.in = true;
                this.tableLoading.out = true;

                // 调用后端统计接口
                axios.get('/statistics/daily', {
                    params: {
                        date: this.statDate
                    }
                }).then(response => {
                    const data = response.data;
                    if (data.code === 200) {
                        const statData = data.data || {};

                        // 更新统计数据
                        this.inTotalCount = statData.inTotalCount || 0;
                        this.inTotalAmount = (statData.inTotalAmount || 0).toFixed(2);

                        this.outTotalCount = statData.outTotalCount || 0;
                        this.outTotalAmount = (statData.outTotalAmount || 0).toFixed(2);

                        // 计算库存变动
                        this.changeCount = this.inTotalCount - this.outTotalCount;
                        this.updateTime = statData.updateTime
                            ? this.formatDateTime(statData.updateTime)
                            : this.formatDateTime(new Date());

                        // 更新明细数据
                        this.inDetailList = statData.inDetailList || [];
                        this.outDetailList = statData.outDetailList || [];

                        // 更新图表
                        this.initPieCharts();
                    } else {
                        this.$message.error('加载统计数据失败：' + (data.msg || '未知错误'));
                    }
                }).catch(error => {
                    console.error('统计数据加载失败：', error);
                    this.$message.error('系统错误，无法加载统计数据');
                }).finally(() => {
                    // 关闭加载
                    this.loading = false;
                    this.tableLoading.in = false;
                    this.tableLoading.out = false;
                });
            },

            // 格式化日期时间显示
            formatDateTime(dateStr) {
                const date = new Date(dateStr);
                return date.toLocaleString('zh-CN', {
                    hour12: false,
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                }).replace(/\//g, '-');
            },

            // 初始化两个扇形图
            initPieCharts() {
                // 处理入库数据为饼图所需格式
                const inPieData = this.processPieData(this.inDetailList, 'in');
                // 处理出库数据为饼图所需格式
                const outPieData = this.processPieData(this.outDetailList, 'out');

                // 初始化入库饼图
                this.initSinglePieChart('inPieChart', inPieData, '入库数量');

                // 初始化出库饼图
                this.initSinglePieChart('outPieChart', outPieData, '出库数量');

                // 监听窗口大小变化，自动调整图表尺寸
                window.addEventListener('resize', () => {
                    if (this.inPieChart) this.inPieChart.resize();
                    if (this.outPieChart) this.outPieChart.resize();
                });
            },

            // 处理数据为饼图所需格式
            processPieData(detailList, type) {
                // 按商品名称分组统计数量
                const productMap = {};

                detailList.forEach(item => {
                    const name = item.productName || '未知商品';
                    if (productMap[name]) {
                        productMap[name] += item.quantity || 0;
                    } else {
                        productMap[name] = item.quantity || 0;
                    }
                });

                // 转换为饼图所需的数据格式
                const pieData = Object.keys(productMap).map(name => ({
                    name: name,
                    value: productMap[name]
                }));

                // 如果没有数据，显示提示
                if (pieData.length === 0) {
                    pieData.push({
                        name: '无数据',
                        value: 1
                    });
                }

                return pieData;
            },

            // 初始化单个饼图 - 主要修改了颜色方案
            initSinglePieChart(elementId, data, legendName) {
                // 获取DOM元素
                const chartDom = document.getElementById(elementId);
                if (!chartDom) return;

                // 如果已有实例，先销毁
                if (elementId === 'inPieChart' && this.inPieChart) {
                    this.inPieChart.dispose();
                } else if (elementId === 'outPieChart' && this.outPieChart) {
                    this.outPieChart.dispose();
                }

                // 初始化图表实例
                const chart = echarts.init(chartDom);
                chart.clear();

                // 设置图表实例引用
                if (elementId === 'inPieChart') {
                    this.inPieChart = chart;
                } else {
                    this.outPieChart = chart;
                }

                // 新的颜色方案 - 增强对比度，使用差异更大的颜色
                const colorPalette = [
                    '#FF5733', // 鲜艳红橙
                    '#33FF57', // 亮绿
                    '#3357FF', // 亮蓝
                    '#F3FF33', // 亮黄
                    '#FF33F3', // 粉红
                    '#33FFF3', // 青蓝
                    '#F333FF', // 亮紫
                    '#FF9933', // 橙
                    '#9933FF', // 紫
                    '#33FF99', // 浅绿
                    '#FF3333', // 红
                    '#3333FF', // 蓝
                    '#99FF33', // 黄绿
                    '#33FFCC', // 青绿
                    '#CC33FF'  // 深粉紫
                ];

                // 饼图配置
                const option = {
                    color: colorPalette,
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} 件 ({d}%)',
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        borderColor: '#eee',
                        borderWidth: 1,
                        textStyle: { color: '#333' },
                        padding: 10,
                        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: data.length > 5 ? 10 : 'center',
                        top: 'center',
                        bottom: data.length > 5 ? 'auto' : 10,
                        orient: data.length > 5 ? 'vertical' : 'horizontal',
                        textStyle: { color: '#666' },
                        formatter: function(name) {
                            // 处理过长的名称
                            if (name.length > 6) {
                                return name.substring(0, 6) + '...';
                            }
                            return name;
                        }
                    },
                    series: [
                        {
                            name: legendName,
                            type: 'pie',
                            radius: data.length === 1 && data[0].name === '无数据' ? ['60%', '80%'] : ['40%', '70%'],
                            center: ['50%', '50%'],
                            avoidLabelOverlap: false,
                            itemStyle: {
                                borderRadius: 6,
                                borderColor: '#fff',
                                borderWidth: 2,
                                shadowBlur: 4,
                                shadowColor: 'rgba(0,0,0,0.1)'
                            },
                            label: {
                                show: false,
                                position: 'center'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: 16,
                                    fontWeight: 'bold',
                                    color: '#333'
                                }
                            },
                            labelLine: {
                                show: false
                            },
                            data: data
                        }
                    ]
                };

                // 无数据时的特殊处理
                if (data.length === 1 && data[0].name === '无数据') {
                    option.series[0].label.show = true;
                    option.series[0].label.formatter = '无数据';
                    option.series[0].label.fontSize = 14;
                    option.series[0].label.color = '#999';
                    option.legend.show = false;
                }

                // 设置图表配置
                chart.setOption(option);
            }
        },
        // 页面销毁时清除图表实例
        beforeDestroy() {
            if (this.inPieChart) this.inPieChart.dispose();
            if (this.outPieChart) this.outPieChart.dispose();
            window.removeEventListener('resize', () => {});
        }
    });
</script>
</body>
</html>